package com.lbj.metalmax.p001

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.work.*
import com.lbj.metalmax.R
import kotlinx.android.synthetic.main.activity_worker.*

const val INPUT_KEY = "input_key"
const val OUTPUT_KEY = "output_key"
const val SP_NAME = "sp_name"

/**
 * 实现 SharedPreferences 接口，监听内容变化
 */
class WorkerActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

    // 获取 WorkManager 实例
    private val workManager = WorkManager.getInstance(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_worker)

        updateText()

        val sp = getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        sp.registerOnSharedPreferenceChangeListener(this)
    }

    fun onOneTimeWorkClick(view: View) {
        // 创建一个单次执行的工作，指定工作者
        val work = OneTimeWorkRequestBuilder<MyWorker>()
            .build()
        // 执行工作
        workManager.enqueue(work)

        val workRequest = OneTimeWorkRequest.from(MyWorker::class.java)
    }

    fun onOneTimeConstraintWorkClick(view: View) {
        // 创建约束条件,网络连接时
        val constraint = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()
        // 创建一个单次执行的工作，指定工作者
        val work = OneTimeWorkRequestBuilder<MyWorker>()
            .setConstraints(constraint) // 添加约束条件

            .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
            .build()
        // 执行工作
        workManager.enqueue(work)
    }

    fun onOneTimeDataWorkClick(view: View) {
        // 创建传递的数据类型,等同于使用  Pair("key","value")
        val data = workDataOf(INPUT_KEY to "传递给 doWork() 方法的数据")
        // 创建单次任务，并指定工作者
        val work = OneTimeWorkRequestBuilder<MyWorker>()
            .setInputData(data)
            .build()
        // 执行工作
        workManager.enqueue(work)

        // 监听任务执行过程
        workManager.getWorkInfoByIdLiveData(work.id).observe(this) {
            Log.d("WorkInfo", "state:${it.state}")
            if (it.state == WorkInfo.State.SUCCEEDED) {
                // 当状态成功时，获取到数据
                val outputData = it.outputData.getString(OUTPUT_KEY)
                Log.d("WorkInfo", "从doWork()传递过来的数据：$outputData")
            }
        }
    }

    fun onMoreWorkClick(view: View) {
        val workA = OneTimeWorkRequestBuilder<MyWorker>()
            .setInputData(workDataOf(INPUT_KEY to "A"))
            .build()
        val workB = OneTimeWorkRequestBuilder<MyWorker>()
            .setInputData(workDataOf(Pair(INPUT_KEY, "B")))
            .build()

        workManager
            .beginWith(workA)
            .then(workB)
            .enqueue()
    }

    private fun updateText() {
        val sp = getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        tvNum1.text = sp.getInt("A", 0).toString()
        tvNum2.text = sp.getInt("B", 0).toString()
    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        updateText()
    }
}